package com.scu.bank.handler;

import com.scu.bank.core.exception.AuthException;
import com.scu.bank.core.exception.ServiceException;
import com.scu.bank.core.jo.Result;
import com.scu.bank.core.jo.ResultCode;
import com.scu.bank.core.jo.ResultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class CommonExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger(CommonExceptionHandler.class);
    private static Logger rootLogger = LoggerFactory.getLogger("");

    @ResponseBody
    @ExceptionHandler(Throwable.class)
    public Result exceptionHandler(HttpServletRequest request,Throwable e) {
        logger.error(e.getMessage(), e);
        return this.error(request,e);
    }

    /**
     * 401处理
     * @param e
     * @return
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AuthException.class)
    public Result UserAccessExceptionHandler(AuthException e) {
        if(rootLogger.isErrorEnabled()) {
            // 打印日志
        }
        return ResultGenerator.genFailResult(e.getMessage());
    }

    private Result error(HttpServletRequest request,Throwable e) {
        Result result = new Result();
        if (e instanceof ServiceException) {//业务失败的异常，如“账号或密码错误”
            result.setCode(ResultCode.FAIL).setMessage(e.getMessage());
            logger.info(e.getMessage());
        }else if (e instanceof NoHandlerFoundException) {
            result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在");
        } else if (e instanceof ServletException) {
            result.setCode(ResultCode.FAIL).setMessage(e.getMessage());
        } else {
            result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误，请联系管理员");
            logger.error(e.getMessage(), e);
        }

        return result;
    }
}
